﻿using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

using SIMSProject.ControlTemplates.SIMSProject;
using Microsoft.SharePoint.WebControls;
using SIMSProject.Common;
using System.Data;
using SIMSProject.Common;

namespace SIMSProject.Views.Inventory.MaterialRequest
{
    public partial class MaterialRequestUserControl : UserControl
    {
        SPItem item = SPContext.Current.Item;
        SPWeb web = SPContext.Current.Web;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            MaterialAdding materialAddingControl = (MaterialAdding)Page.LoadControl("~/_CONTROLTEMPLATES/SIMSProject/MaterialAdding.ascx");
            materialAddingControl.ParentListName = "Material Request";
            materialAddingControl.SetSessionName(this.hdfSessionName.Value);
            this.phMaterialAddingModule.Controls.Add(materialAddingControl);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.LoadData();
                this.btReject.Attributes.Add("onclick", "if($('#tdSupervisorComment textarea').val()==''){alert('Please enter comment!');return false;}return confirm('Are you sure to reject this Request ?')");
                this.btDirectorReject.Attributes.Add("onclick", "if($('#tdDirectorComment textarea').val()==''){alert('Please enter comment!');return false;}return confirm('Are you sure to reject this Request ?')");
            }
            this.ShowHideControlInForm();
            if (!IsPostBack)
            {
                this.hdfSessionName.Value = Guid.NewGuid().ToString().Replace("-", "");
            }
            
        }

        #region
        private void LoadData()
        {
            if (SPContext.Current.FormContext.FormMode == Microsoft.SharePoint.WebControls.SPControlMode.New)
            {
                this.lblUserField.Text = SPContext.Current.Web.CurrentUser.Name;
                this.lblUserField.Visible = true;
                this.hdfStatus.Value = "Initiating";
                this.dtfProcessedDate.Visible = false;
            }
        }
        #endregion

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit || SPContext.Current.FormContext.FormMode == SPControlMode.New)
            {
                SPContext.Current.FormContext.OnSaveHandler += this.CustomSaveHandler;
            }
        }

        private void CustomSaveHandler(object o, EventArgs e)
        {

        }

        protected void btSave_Click(object o, EventArgs e)
        {
            if (Page.IsValid)
            {
                DateTime expectedDate = Convert.ToDateTime(dtfExpectedDate.Value);
                if (expectedDate.CompareTo(DateTime.Today) < 0)
                {
                    dtfExpectedDate.IsValid = false;
                    dtfExpectedDate.ErrorMessage = "Expected Date must set to be in the future";
                    return;
                }

                DataTable dt = Session[this.hdfSessionName.Value] as DataTable;
                if (dt != null && dt.Rows.Count != 0)
                {

                    if (string.Equals(this.hdfStatus.Value, "Initiating"))
                    {
                        SPContext.Current.Item["Status"] = "Pending";
                        SPContext.Current.Web.AllowUnsafeUpdates = true;
                        SaveButton.SaveItem(SPContext.Current, false, string.Empty);
                        this.UpdateMaterialDetail();
                        Common.Common.SendEmail(web, Common.Common.GetEmailAddressesFromName(Constant.Groups.Supervisor), string.Empty, "[SIMS Material Request][New Request]# " + item["Request Code"], this.BuiMainContent());
                    }

                    SPContext.Current.Item["Title"] = SPContext.Current.Web.CurrentUser.Name;
                    SPContext.Current.Web.AllowUnsafeUpdates = true;
                    SaveButton.SaveItem(SPContext.Current, false, string.Empty);
                    this.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                }
                else
                {
                    this.Page.Response.Write("<script type='text/javascript'>window.alert('Please insert some Material to this Request');</script>");
                }
            }
        }

        private void ShowHideControlInForm()
        {
            if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit)
            {
                string status = item["Status"].ToString();
                switch (status)
                {
                    case "Initiating":
                        {
                            this.btSendRequest.Visible = true;
                            break;
                        }
                    case "Pending":
                        {

                            if (web.IsCurrentUserMemberOfGroup(web.Groups["Inventory Supervisor"].ID))
                            {
                                this.btApprove.Visible = true;
                                this.btReject.Visible = true;
                                this.btSentToDirector.Visible = true;
                                this.ProcessSection.Visible = true;
                            }
                            else
                            {
                                this.txtComment.ControlMode = SPControlMode.Display;
                            }
                            break;
                        }
                    case "Director Review":
                        {
                            this.ProcessSection.Visible = true;
                            this.txtComment.ControlMode = SPControlMode.Display;
                            this.DirectorSection.Visible = true;
                            if (web.IsCurrentUserMemberOfGroup(web.Groups["Director"].ID))
                            {
                                this.btDirectorReject.Visible = true;
                                this.btDirectorApprove.Visible = true;
                            }
                            else
                            {
                                this.ffDirectorComment.ControlMode = SPControlMode.Display;
                            }
                            break;
                        }
                    case "Approved":
                        {

                            this.ProcessSection.Visible = true;
                            this.txtComment.ControlMode = SPControlMode.Display;
                            if (item["Director"]!=null)
                            {
                                this.DirectorSection.Visible = true;
                                this.ffDirectorComment.ControlMode = SPControlMode.Display;
                            }
                            this.InventorySection.Visible = true;
                            if (web.IsCurrentUserMemberOfGroup(web.Groups["Inventory Manager"].ID))
                            {
                                this.btFinish.Visible = true;
                            }
                            else
                            {
                                this.txtInventoryComment.ControlMode = SPControlMode.Display;
                            }
                            break;
                        }
                    case "Finished":
                    case "Rejected":
                        {
                            this.ProcessSection.Visible = true;
                            this.txtComment.ControlMode = SPControlMode.Display;
                            this.DirectorSection.Visible = true;
                            this.ffDirectorComment.ControlMode = SPControlMode.Display;
                            this.InventorySection.Visible = true;
                            this.txtInventoryComment.ControlMode = SPControlMode.Display;
                            break;
                        }
                }

                this.dtfExpectedDate.ControlMode = SPControlMode.Display;
                this.ffDescription.ControlMode = SPControlMode.Display;
                this.ffRequestCode.ControlMode = SPControlMode.Display;
            }
            else
            {
                if (SPContext.Current.FormContext.FormMode == SPControlMode.New)
                {
                    this.btSendRequest.Visible = true;
                }
                else
                {
                    this.ProcessSection.Visible = true;
                    this.txtComment.ControlMode = SPControlMode.Display;
                    if (item["Director"] != null)
                    {
                        this.DirectorSection.Visible = true;
                        this.ffDirectorComment.ControlMode = SPControlMode.Display;
                    }
                    this.InventorySection.Visible = true;
                    this.txtInventoryComment.ControlMode = SPControlMode.Display;
                }
            }

           
        }

        private void AddNewMaterialTracking()
        {
            // Add Product Tracking header
            SPList list = web.Lists["Material Tracking"];
            SPListItem newItem = list.Items.Add();
            newItem["Title"] = "Tracking for Request : " + SPContext.Current.Item["Request Code"].ToString();
            newItem["Tracking Type"] = "Export";
            newItem["Description"] = "Requestor : " + getUser(Constant.MaterialRequest.CreatedBy).Name + "\nRequest Date : " + item["Created"] + "\nDescription : " + item["Description"];
            newItem["Month"] = DateTime.Now.Month;
            newItem["Year"] = DateTime.Now.Year;
            newItem.Update();

            // Add Product tracking detail
            int id = newItem.ID;
            int totalQuantity = 0;
            DataTable MaterialTable = (DataTable)Session[this.hdfSessionName.Value];

            SPList childList = web.Lists["Material Tracking Detail"];

            for (int i = 0; i < MaterialTable.Rows.Count; i++)
            {
                SPQuery query = new SPQuery();
                query.Query = "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + id.ToString() + "</Value></Eq><Eq><FieldRef Name='Material_x0020_Id' /><Value Type='Text'>" + Convert.ToString(MaterialTable.Rows[i]["id"]) + "</Value></Eq></And></Where>";
                if (childList.GetItems(query).Count == 0)
                {
                    SPListItem itemDetail = childList.Items.Add();
                    itemDetail["Title"] = id;
                    itemDetail["Material Name"] = MaterialTable.Rows[i]["MaterialName"];
                    itemDetail["Material Code"] = MaterialTable.Rows[i]["MaterialCode"];
                    itemDetail["Material Id"] = MaterialTable.Rows[i]["id"];
                    itemDetail["Quantity"] = MaterialTable.Rows[i]["Quantity"];
                    itemDetail.Update();
                }
                else
                {
                    SPListItem itemDetail = childList.GetItems(query)[0];
                    itemDetail["Quantity"] = MaterialTable.Rows[i]["Quantity"];
                    itemDetail.Update();
                }

                int temp = 0;
                Int32.TryParse(Convert.ToString(MaterialTable.Rows[i]["Quantity"]), out temp);
                totalQuantity += temp;
            }

            newItem["Total Quantity"] = totalQuantity;
            newItem.Update();
            this.UpdateMaterial();
        }

        protected SPUser getUser(string field)
        {
            string strUser = SPContext.Current.Item[field].ToString();
            string[] information = strUser.Split(';');
            SPUser user = SPContext.Current.Web.SiteUsers.GetByID(Convert.ToInt32(information[0]));
            return user;
        }

        private void UpdateMaterial()
        {
            DataTable dt = Session[this.hdfSessionName.Value] as DataTable;
            int id, quantity;
            SPList listProduct = web.Lists["Material"];
            SPListItem item;
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    id = (int)dr["id"];
                    quantity = (int)dr["Quantity"];
                    item = listProduct.GetItemById(id);
                    int currentQuantity = Convert.ToInt32(item["Quantity"]);
                    item["Quantity"] = currentQuantity - quantity;
                    item.Update();
                }
            }
        }

        private void UpdateMaterialDetail()
        {
            int id = SPContext.Current.Item.ID;
            int totalQuantity = 0;
            DataTable materialTable = (DataTable)Session[this.hdfSessionName.Value];

            SPList childList = SPContext.Current.Web.Lists["Material Request Detail"];

            for (int i = 0; i < materialTable.Rows.Count; i++)
            {
                SPQuery query = new SPQuery();
                query.Query = "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + id.ToString() + "</Value></Eq><Eq><FieldRef Name='Material_x0020_Id' /><Value Type='Text'>" + Convert.ToString(materialTable.Rows[i]["id"]) + "</Value></Eq></And></Where>";
                if (childList.GetItems(query).Count == 0)
                {
                    SPListItem item = childList.Items.Add();
                    item["Title"] = id;
                    item["Material Name"] = materialTable.Rows[i]["MaterialName"];
                    item["Material Code"] = materialTable.Rows[i]["MaterialCode"];
                    item["Material Id"] = materialTable.Rows[i]["id"];
                    item["Quantity"] = materialTable.Rows[i]["Quantity"];
                    item.Update();
                }
                else
                {
                    SPListItem item = childList.GetItems(query)[0];
                    item["Quantity"] = materialTable.Rows[i]["Quantity"];
                    item.Update();
                }

                int temp = 0;
                Int32.TryParse(Convert.ToString(materialTable.Rows[i]["Quantity"]), out temp);
                totalQuantity += temp;
            }

            SPContext.Current.Item["Total Quantity"] = totalQuantity;
            SaveButton.SaveItem(SPContext.Current, false, string.Empty);
        }

        private bool CheckMaterial()
        {
            DataTable dt = Session[this.hdfSessionName.Value] as DataTable;
            if (dt != null && dt.Rows.Count != 0)
            {
                string message = string.Empty;

                foreach (DataRow dr in dt.Rows)
                {
                    int id = 0;
                    Int32.TryParse(Convert.ToString(dr["id"]), out id);
                    int quantity = 0;
                    Int32.TryParse(Convert.ToString(dr["Quantity"]), out quantity);

                    SPListItem material = SPContext.Current.Web.Lists["Material"].GetItemById(id);

                    int materialQuantity = 0;
                    Int32.TryParse(Convert.ToString(material["Quantity"]), out materialQuantity);

                    if (quantity > materialQuantity)
                    {
                        message += "The quanlity of " + material["Title"] + " is not enough\\r\\n";

                    }
                }
                if (message != string.Empty)
                {
                    message = "<script type='text/javascript'>window.alert('" + message + "');</script>";
                    this.Page.Response.Write(message);
                    return false;
                }
                else return true;
            }
            else
            {
                this.Page.Response.Write("<script type='text/javascript'>window.alert('Please insert some Material to this tracking');</script>");
                return false;
            }
        }

        protected void btApprove_Click(object sender, EventArgs e)
        {
            SPContext.Current.Item["Status"] = "Approved";
            SPContext.Current.Item["Processor"] = SPContext.Current.Web.CurrentUser;
            SPContext.Current.Item["Processed Date"] = DateTime.Now;

            SaveButton.SaveItem(SPContext.Current, false, string.Empty);
            SPUser user = getUser("Created By");
            
            Common.Common.SendEmail(web, Common.Common.GetEmailAddressesFromName(Constant.Groups.InventoryManager), Common.Common.GetEmailAddressesFromName(Constant.Groups.Director) + Common.Common.GetEmailAddressesFromName(user.LoginName), "[SIMS Material Request][Approved Request]# " + item["Request Code"], this.BuiMainContent());
            this.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
        }

        protected void btDirectorApprove_Click(object sender, EventArgs e)
        {
            SPContext.Current.Item["Status"] = "Approved";
            SPContext.Current.Item["Director"] = SPContext.Current.Web.CurrentUser;
            SPContext.Current.Item["Approved Date"] = DateTime.Now;

            SaveButton.SaveItem(SPContext.Current, false, string.Empty);
            SPUser created = getUser("Created By");
            SPUser supervisor = getUser("Processor");

            Common.Common.SendEmail(web, Common.Common.GetEmailAddressesFromName(Constant.Groups.InventoryManager), Common.Common.GetEmailAddressesFromName(supervisor.LoginName) + Common.Common.GetEmailAddressesFromName(created.LoginName), "[SIMS Material Request][Approved Request]# " + item["Request Code"], this.BuiMainContent());
            
            SaveButton.SaveItem(SPContext.Current, false, string.Empty);
            this.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");

        }

        protected void btReject_Click(object sender, EventArgs e)
        {
            SPContext.Current.Item["Status"] = "Rejected";
            SPContext.Current.Item["Processor"] = SPContext.Current.Web.CurrentUser;
            SPContext.Current.Item["Processed Date"] = DateTime.Now;

            SaveButton.SaveItem(SPContext.Current, false, string.Empty);

            SPUser created = getUser("Created By");
            
            Common.Common.SendEmail(web, Common.Common.GetEmailAddressesFromName(created.LoginName), Common.Common.GetEmailAddressesFromName(Constant.Groups.Director), "[SIMS Material Request][Rejected Request]# " + item["Request Code"], this.BuiMainContent());
            
            this.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
        }

        protected void btSentToDirector_Click(object sender, EventArgs e)
        {
            SPContext.Current.Item["Status"] = "Director Review";
            SPContext.Current.Item["Processor"] = SPContext.Current.Web.CurrentUser;
            SPContext.Current.Item["Processed Date"] = DateTime.Now;

            SaveButton.SaveItem(SPContext.Current, false, string.Empty);
            
            SPUser created = getUser("Created By");
            
            Common.Common.SendEmail(web, Common.Common.GetEmailAddressesFromName(Constant.Groups.Director), Common.Common.GetEmailAddressesFromName(created.LoginName), "[SIMS Material Request][Director Review Request]# " + item["Request Code"], this.BuiMainContent());
            
            this.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
        }

        protected void btFinish_Click(object sender, EventArgs e)
        {
            if (this.CheckMaterial())
            {
                SPContext.Current.Item["Status"] = "Finished";
                SPContext.Current.Item["InventoryManager"] = SPContext.Current.Web.CurrentUser;
                SPContext.Current.Item["Finished Date"] = DateTime.Now;
                SaveButton.SaveItem(SPContext.Current, false, string.Empty);
                this.AddNewMaterialTracking();

                SPUser created = getUser("Created By");
                SPUser supervisor = getUser("Processor");

                if (item[Constant.MaterialRequest.Director] != null)
                {
                    SPUser director = getUser("Director");
                    Common.Common.SendEmail(web, Common.Common.GetEmailAddressesFromName(created.LoginName), Common.Common.GetEmailAddressesFromName(director.LoginName) + Common.Common.GetEmailAddressesFromName(supervisor.LoginName), "[SIMS Material Request][Finished Request]# " + item["Request Code"], this.BuiMainContent());
                }
                else
                {
                    Common.Common.SendEmail(web, Common.Common.GetEmailAddressesFromName(created.LoginName), Common.Common.GetEmailAddressesFromName(supervisor.LoginName), "[SIMS Material Request][Finished Request]# " + item["Request Code"], this.BuiMainContent());
                }
                this.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
            }
        }

        protected void btDirectorReject_Click(object sender, EventArgs e)
        {
            SPContext.Current.Item["Status"] = "Rejected";
            SPContext.Current.Item["Director"] = SPContext.Current.Web.CurrentUser;
            SPContext.Current.Item["Approved Date"] = DateTime.Now;

            SaveButton.SaveItem(SPContext.Current, false, string.Empty);
            this.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
        }

        private string BuiMainContent()
        {
            string content = string.Empty;

            content += "<b>Request Code: </b>" + item[Constant.MaterialRequest.RequestCode] + "<br/>";
            content += "<b>Requestor: </b>" + item[Constant.MaterialRequest.Requestor] + "<br/>";
            content += "<b>Requested Date: </b>" + item[Constant.MaterialRequest.Created] + "<br/>";
            content += "<b>Expected Date: </b>" + item[Constant.MaterialRequest.ExpectedDate] + "<br/>";
            content += "<b>Description : </b>" + item[Constant.MaterialRequest.Description] + "<br/><hr/>";

            switch (item["Status"].ToString())
            {
                case "Pending":
                    {
                        break;
                    }
                case "Director Review":
                    {
                        SPUser processor = getUser(Common.Constant.MaterialRequest.Processor);
                        content += "<b>Processor            :&nbsp;</b>" + processor.Name + "<br/>";
                        content += "<b>Date                 :&nbsp;</b>" + item[Common.Constant.MaterialRequest.ProcessorDate] + "<br/>";
                        content += "<b>Comment              :&nbsp;</b>" + item[Common.Constant.MaterialRequest.Comment] + "<br/>";
                        break;
                    }
                case "Approved":
                    {
                        if (item[Constant.MaterialRequest.Director] == null)
                        {
                            SPUser processor = getUser(Common.Constant.MaterialRequest.Processor);
                            content += "<b>Processor            :&nbsp;</b>" +processor.Name + "<br/>";
                            content += "<b>Date                 :&nbsp;</b>" + item[Common.Constant.MaterialRequest.ProcessorDate] + "<br/>";
                            content += "<b>Comment              :&nbsp;</b>" + item[Common.Constant.MaterialRequest.Comment] + "<br/>";
                        }
                        else
                        {
                            SPUser director = getUser(Common.Constant.MaterialRequest.Director);
                            content += "<b>Director             :&nbsp;</b>" + director.Name + "<br/>";
                            content += "<b>Date                 :&nbsp;</b>" + item[Common.Constant.MaterialRequest.ApprovedDate] + "<br/>";
                            content += "<b>Comment              :&nbsp;</b>" + item[Common.Constant.MaterialRequest.DirectorComment] + "<br/>";
                        }
                        break;
                    }
                case "Finised":
                    {
                        SPUser inventory = getUser(Common.Constant.MaterialRequest.InventoryManager);
                        content += "<b>Inventory Manager    :&nbsp;</b>" + inventory.Name + "<br/>";
                        content += "<b>Date                 :&nbsp;</b>" + item[Common.Constant.MaterialRequest.FinishedDate] + "<br/>";
                        content += "<b>Comment              :&nbsp;</b>" + item[Common.Constant.MaterialRequest.InventoryComment] + "<br/>";
                        break;
                    }
                case "Rejected":
                    {
                        if (item[Constant.MaterialRequest.Director] == null)
                        {
                            SPUser processor = getUser(Common.Constant.MaterialRequest.Processor);
                            content += "<b>Processor            :&nbsp;</b>" + processor.Name + "<br/>";
                            content += "<b>Date                 :&nbsp;</b>" + item[Common.Constant.MaterialRequest.ProcessorDate] + "<br/>";
                            content += "<b>Comment              :&nbsp;</b>" + item[Common.Constant.MaterialRequest.Comment] + "<br/>";
                        }
                        else
                        {
                            SPUser director = getUser(Common.Constant.MaterialRequest.Director);
                            content += "<b>Director             :&nbsp;</b>" + director.Name + "<br/>";
                            content += "<b>Date                 :&nbsp;</b>" + item[Common.Constant.MaterialRequest.ApprovedDate] + "<br/>";
                            content += "<b>Comment              :&nbsp;</b>" + item[Common.Constant.MaterialRequest.DirectorComment] + "<br/>";
                        }
                        break;
                    }
                    
            }

            string path = Request.Url.Authority + "/Lists/Order/DispForm.aspx?ID=" + item["ID"].ToString();

            content += "<hr/><a href='" + path +"'>Click Here to Access the Material Request</a>";

            return content;
        }
    }
}
